import React, { Component, Fragment } from 'react';
import { formatMessage, FormattedMessage } from 'umi-plugin-react/locale';
import { Form, Input, Upload, Select, Button } from 'antd';
import { connect } from 'dva';
import styles from './BaseView.less';
// import { getTimeDistance } from '@/utils/utils';
import PropTypes from 'prop-types'
import { post } from '@/utils/request';
import * as api from '@/constants/api';
import { toast, notify, alert, confirm } from '@/utils/utils';
import * as constant from '@/constants';

const FormItem = Form.Item;
const { Option } = Select;

const headers = {};
const token = localStorage.getItem(constant.STORAGE_TOKEN_KEY);
if(token){
  headers.Authorization = `Bearer ${token}`;
  headers['upload-type'] = 'avatar';
}

// 头像组件 方便以后独立，增加裁剪之类的功能
class AvatarView extends Component{

  static propTypes = {
    avatar: PropTypes.string,
    uploadSuc: PropTypes.func,
  }
  
  static defaultProps = {
    avatar: '',
    uploadSuc: ()=>{},
  };

  constructor(props) {
    super(props);

    this.state = {
      fileList: [],
    }
  }

  onChange = (params)=>{
    const {uploadSuc} = this.props;
    this.setState({
      fileList: [...params.fileList]
    })
    if(params.file.status==='done' && params.file.response && params.file.response.code===2000){
      toast('头像上传成功');
      const imgUrl = params.file.response.data;
      uploadSuc && uploadSuc(imgUrl);
    }
  }

  beforeUpload = file=>{
    const extValid = ['.jpg', '.png', '.jpeg', '.gif'].some(ext=>file.name.endsWith(ext));
    if(!extValid){
      toast('图片格式不对', 'error')
      return false;
    }

    if(file.size/1024/1024 > 5){
      toast('图片过大，不能大于5M', 'error')
      return false;
    }

    return true;
  }

  render() {

    const {avatar} = this.props;
    const {fileList} = this.state;

    return (
      <Fragment>
        <div className={styles.avatar_title}>
          <FormattedMessage id="app.settings.basic.avatar" defaultMessage="Avatar" />
        </div>
        <div className={styles.avatar}>
          <img src={avatar} alt="avatar" />
        </div>
        <Upload action={api.UPLOAD} headers={headers} onChange={this.onChange} fileList={fileList} beforeUpload={this.beforeUpload} showUploadList={false}>
          <div className={styles.button_view}>
            <Button icon="upload">
              <FormattedMessage id="app.settings.basic.change-avatar" defaultMessage="Change avatar" />
            </Button>
          </div>
        </Upload>
      </Fragment>
    );
  }
}

@connect(({ user, loading }) => ({
  currentUser: user.currentUser,
  submiting: loading.effects['user/updateCurrent'],
}))
@Form.create()
class BaseView extends Component {
  componentDidMount() {
    this.setBaseInfo();
  }

  setBaseInfo = () => {
    const { currentUser, form } = this.props;
    const obj = {};
    Object.keys(form.getFieldsValue()).forEach(key => {
      obj[key] = currentUser[key] || null;
    });
    form.setFieldsValue(obj);
  };

  getAvatarURL() {
    const { currentUser } = this.props;
    if (currentUser.avatar) {
      return api.HOST_RES+currentUser.avatar;
    }
    const url = 'https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png';
    return url;
  }

  getViewDom = ref => {
    this.view = ref;
  };

  uploadSuc = (imgUrl)=>{
    const {dispatch} = this.props;
    dispatch({
      type: 'user/updateAvatar',
      payload: imgUrl,
    })
  }

  handleSubmit = (e) => {
    e && e.preventDefault();
    const { dispatch, form, currentUser } = this.props;
    form.validateFields((errors, values)=>{
      if(errors){
        return;
      }

      // update profile
      dispatch({
        type: 'user/updateCurrent',
        payload: {...values},
      }).then(()=>{
        toast('更新成功')
      })
    });
  }

  render() {
    const {
      form: { getFieldDecorator },
      submiting,
    } = this.props;
    return (
      <div className={styles.baseView} ref={this.getViewDom}>
        <div className={styles.left}>
          <Form layout="vertical" onSubmit={this.handleSubmit} hideRequiredMark>
            <FormItem label="账号">
              {getFieldDecorator('account', {
                rules: []
              })(<Input disabled />)}
            </FormItem>
            <FormItem label={formatMessage({ id: 'app.settings.basic.email' })}>
              {getFieldDecorator('email', {
                rules: [
                  {
                    required: true,
                    message: formatMessage({ id: 'app.settings.basic.email-message' }, {}),
                  },
                ],
              })(<Input />)}
            </FormItem>
            <FormItem label={formatMessage({ id: 'app.settings.basic.nickname' })}>
              {getFieldDecorator('name', {
                rules: [
                  {
                    required: true,
                    message: formatMessage({ id: 'app.settings.basic.nickname-message' }, {}),
                  },
                ],
              })(<Input />)}
            </FormItem>
            <FormItem label="手机号码">
              {getFieldDecorator('phone', {
                rules: [
                  {
                    required: true,
                    message: '手机号码不能为空',
                  },
                ],
              })(<Input />)}
            </FormItem>
            <FormItem label={formatMessage({ id: 'app.settings.basic.profile' })}>
              {getFieldDecorator('profile', {
                rules: [
                  {
                    required: false,
                    message: formatMessage({ id: 'app.settings.basic.profile-message' }, {}),
                  },
                ],
              })(
                <Input.TextArea
                  placeholder={formatMessage({ id: 'app.settings.basic.profile-placeholder' })}
                  rows={4}
                />
              )}
            </FormItem>
            <Button loading={submiting} type="primary" onClick={this.handleSubmit}>
              <FormattedMessage
                id="app.settings.basic.update"
                defaultMessage="Update Information"
              />
            </Button>
          </Form>
        </div>
        <div className={styles.right}>
          <AvatarView avatar={this.getAvatarURL()} uploadSuc={this.uploadSuc} />
        </div>
      </div>
    );
  }
}

export default BaseView;
